<template>
    <ElContainer :style="{ minHeight: '100vh' }">
        <el-main>
            <headerstepsVue v-bind="{ active, successstatus, next }"></headerstepsVue>
            <el-form :model="ruleForm" :rules="rules" ref="rule" label-width="100px" class="demo-ruleForm">
                <el-tabs v-model="active" class="tabs" tab-position="left">
                    <el-tab-pane label="0">
                        <el-form-item label="任务名：" prop="name">
                            <el-input v-model="ruleForm.name"></el-input>
                        </el-form-item>
                        <el-form-item label="任务类型：" prop="type">
                            <el-radio-group v-model="ruleForm.type" :disabled="!!ruleForm.ID">
                                <el-radio label="question">题目练习</el-radio>
                                <el-radio label="video">学习视频</el-radio>
                                <el-radio v-if="!team?.isadmin" label="file">学习资料</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="任务时间：" prop="type">
                            <el-date-picker :default-time="defaultTime" v-model="daterangetime" type="daterange"
                                placeholder="选择时间" />
                        </el-form-item>
                        <!-- <el-form-item label="结束时间：" prop="type">
                            <el-date-picker
                                :default-time="[new Date(2000, 2, 1, 23, 59, 59), new Date(2000, 2, 1, 23, 59, 59)]"
                                v-model="ruleForm.endtime" type="date" placeholder="选择时间" />
                        </el-form-item> -->
                        <div class="row">
                            <div class="col" :class="!ruleForm.ID ? 'text-center' : ''">
                                <el-button @click="next(1)" :style="{
                                    '--el-button-bg-color': '#434343',
                                    '--el-button-border-color': '#434343'
                                }" size="large" type="primary">下一步</el-button>
                            </div>
                            <div v-show="ruleForm.ID" class="col text-right">
                                <el-button type="info" size="large" @click="close">取消</el-button>
                                <el-button @click="submit" type="primary" size="large">保存</el-button>
                            </div>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane v-if="ruleForm.type === 'question'" label="1">
                        <el-form-item label-width="112px" label="任务类型：">
                            题目练习
                        </el-form-item>
                        <el-form-item label-width="112px" label="题目完成目标：">
                            <el-radio-group v-model="num">
                                <el-radio :label="true">以下题目全部完成</el-radio>
                                <el-radio :label="false"><span>以下题目中，完成任意 &nbsp;&nbsp;</span>
                                    <el-input-number :style="{ width: '120px' }" v-model="num2" :min="1"
                                        :max="questionid.length || 1" />
                                    <span>题 &nbsp;&nbsp;</span>
                                </el-radio>
                            </el-radio-group>

                        </el-form-item>
                        <el-form-item label-width="112px" label="题目完成判断：">
                            <span>测试点AC率达到 &nbsp;&nbsp;</span>
                            <el-input-number v-model="ruleForm.questionac" :min="1" :max="100" />
                            <span>&nbsp;&nbsp;%以上，认为题目完成</span>
                        </el-form-item>
                        <el-form-item label="题目范围 ：" label-width="112px">
                            注意: 当前题目练习任务只支持编程题哦!
                        </el-form-item>
                        <div class="row">
                            <Selectquestion v-model="questionid" :removeclick="removeclick" :addclick="addclick"
                                :questionid="questionid" :change="changequestionid" :teamid="teamid">
                            </Selectquestion>
                        </div>
                        <div class="row">
                            <div class="col" :class="!ruleForm.ID ? 'text-center' : ''">
                                <el-button @click="next(2)" :style="{
                                    '--el-button-bg-color': '#434343',
                                    '--el-button-border-color': '#434343'
                                }" size="large" type="primary">下一步</el-button>
                            </div>
                            <div v-show="ruleForm.ID" class="col text-right">
                                <el-button type="info" size="large" @click="close">取消</el-button>
                                <el-button @click="submit" type="primary" size="large">保存</el-button>
                            </div>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane v-else-if="ruleForm.type === 'file'" label="1">
                        <el-form-item label-width="112px" label="任务类型：">
                            学习资料
                        </el-form-item>
                        <el-form-item label-width="112px" label="学习资料目标：">
                            <el-radio-group v-model="num">
                                <el-radio :label="true">学习资料完成</el-radio>
                                <el-radio :label="false"><span>以下文件任意下载 &nbsp;&nbsp;</span>
                                    <el-input-number :style="{ width: '120px' }" :min="1" v-model="num2"
                                        :max="teamfile.length || 1" />
                                    <span>个 &nbsp;&nbsp;</span>
                                </el-radio>
                            </el-radio-group>

                        </el-form-item>
                        <el-form-item label="选择文件 ：" label-width="112px"></el-form-item>
                        <div class="row">
                            <Downloadfile v-model="teamfile" :removeclick="removeclickteamfile"
                                :addclick="addclickteamfile" :questionid="teamfile" :change="chageteamfile"
                                :teamid="teamid"></Downloadfile>
                        </div>
                        <div class="row">
                            <div class="col" :class="!ruleForm.ID ? 'text-center' : ''">
                                <el-button @click="next(2)" :style="{
                                    '--el-button-bg-color': '#434343',
                                    '--el-button-border-color': '#434343'
                                }" size="large" type="primary">下一步</el-button>
                            </div>
                            <div v-show="ruleForm.ID" class="col text-right">
                                <el-button type="info" size="large" @click="close">取消</el-button>
                                <el-button @click="submit" type="primary" size="large">保存</el-button>
                            </div>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane v-else-if="ruleForm.type === 'video'" label="1">
                        <el-form-item label-width="112px" label="任务类型：">
                            观看视频
                        </el-form-item>
                        <el-form-item label-width="112px" label="观看视频目标：">
                            <el-radio-group v-model="num">
                                <el-radio :label="true">以下观看视频完成</el-radio>
                                <el-radio :label="false"><span>以下视频中，完成任意 &nbsp;&nbsp;</span>
                                    <el-input-number :style="{ width: '120px' }" v-model="num2" :min="1"
                                        :max="courses.length || 1" />
                                    <span>个 &nbsp;&nbsp;</span>
                                </el-radio>
                            </el-radio-group>

                        </el-form-item>
                        <el-form-item label-width="112px" label="观看视频判断：">
                            <span>观看视频达到 &nbsp;&nbsp;</span>
                            <el-input-number v-model="ruleForm.questionac" :min="1" :max="100" />
                            <span>&nbsp;&nbsp;%以上，认为观看视频完成</span>
                        </el-form-item>
                        <el-form-item label="视频范围 ：" label-width="112px"></el-form-item>
                        <div class="row">
                            <Selectcourse v-model="courses" :removeclick="removeclickcourse" :addclick="addclickcourse"
                                :questionid="courses" :change="chagecourse" :teamid="teamid"></Selectcourse>
                        </div>
                        <div class="row">
                            <div class="col" :class="!ruleForm.ID ? 'text-center' : ''">
                                <el-button @click="next(2)" :style="{
                                    '--el-button-bg-color': '#434343',
                                    '--el-button-border-color': '#434343'
                                }" size="large" type="primary">下一步</el-button>
                            </div>
                            <div v-show="ruleForm.ID" class="col text-right">
                                <el-button type="info" size="large" @click="close">取消</el-button>
                                <el-button @click="submit" type="primary" size="large">保存</el-button>
                            </div>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="2">
                        <el-form-item label="成员范围：">
                            <el-radio-group v-model="ruleForm.isall">
                                <el-radio :label="true">全部成员</el-radio>
                                <el-radio :label="false">部分成员</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item v-show="!ruleForm.isall" label="任务成员：">
                            <el-cascader :style="{ width: '100%' }" v-model="users" :show-all-levels="false"
                                :props="rops" clearable filterable :options="options">
                            </el-cascader>
                        </el-form-item>
                        <div class="row">
                            <div class="col" :class="!ruleForm.ID ? 'text-center' : ''">
                                <el-button @click="next(3)" :style="{
                                    '--el-button-bg-color': '#434343',
                                    '--el-button-border-color': '#434343'
                                }" size="large" type="primary">下一步</el-button>
                            </div>
                            <div v-show="ruleForm.ID" class="col text-right">
                                <el-button type="info" size="large" @click="close">取消</el-button>
                                <el-button @click="submit" type="primary" size="large">保存</el-button>
                            </div>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="3">
                        <el-form-item label="任务奖励：">
                            <el-input type="textarea" v-model="ruleForm.reward" maxlength="128"
                                placeholder="请输入任务奖励，任务奖励将显示在任务详情中" />
                        </el-form-item>
                        <el-form-item label="任务备注：">
                            <el-input v-model="ruleForm.remarks" maxlength="128" placeholder="请输入任务备注，任务备注将显示在任务详情中" />
                        </el-form-item>
                        <el-form-item label="进度公开：">
                            <el-radio-group v-model="ruleForm.isopen">
                                <el-radio :label="true">公开任务进度，任务成员均可见</el-radio>
                                <el-radio :label="false">隐藏任务进度，仅团队管理员、老师可见</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <div class="row">
                            <div class="col text-center">
                                <el-button type="info" size="large" @click="close">取消</el-button>
                                <el-button @click="submit" type="primary" size="large">完成</el-button>
                            </div>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-main>
    </ElContainer>
</template>


<script setup lang="ts">
import { CascaderOption, dayjs, ElForm, ElMessage } from "element-plus";
import { assign, forEach, groupBy, uniq } from "underscore";
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { RouteLocationRaw, useRouter } from "vue-router";
import { useStore } from "vuex";
import { Teanjob } from "../../admin/views/data";
import { teamjobrules } from "../../admin/views/data/formrules";
import { asyncgetteamfile, asyncselectcourse, asyncteamcreatedorupdatedteamjob } from "../../api";
import { EMstatus, Storekey } from '../../interface';
import Alymodel from "../../mysql_interface/model";
import Studycodemodel from "../../mysql_interface/studycodemodel";
import Selectcourse from '../selectcourse/index.vue';
import Selectquestion from '../selectquestion/index.vue';
import Downloadfile from './downloadfile.vue';
import headerstepsVue from "./headersteps.vue";
const active = ref('0')

/**
 * 是否选择全部
 */
const num = ref(true)
/**
 * 选择数量
 */
const num2 = ref(1)
const p = defineProps<{ teamid: number, options: CascaderOption[], data?: Studycodemodel.Iteamjob, roure: RouteLocationRaw, question: Studycodemodel.Iquestion[], teamusers: Studycodemodel.Iteamuser[], isAdmin?: boolean, team?: Studycodemodel.Iteam }>()

const rops = { multiple: true }

const users = ref<number[][]>([])

const store = useStore(Storekey)

const team = computed(() => {
    if (p.isAdmin) {
        return p.team
    }
    return store.state.team?.rows.find(e => e.ID === p.teamid)
})

const defaultTime = ref<[Date, Date]>([
    new Date(2000, 1, 1, 0, 0, 0),
    new Date(2000, 2, 1, 23, 59, 59),
])

type Isuccessstatus = [EMstatus, EMstatus, EMstatus, EMstatus]
const successstatus = ref<Isuccessstatus>(['finish', 'wait', 'wait', 'wait'])
const router = useRouter()
const rules = teamjobrules;
const ruleForm = reactive<Studycodemodel.Iteamjob>(
    assign({},
        Teanjob,
    )
);
function close() {
    router.go(-1)
}

const questionid = ref<Studycodemodel.Iquestion[]>([])
const courses = ref<Alymodel.IMcourse[]>([])
const teamfile = ref<Studycodemodel.Iteamfile[]>([])
const daterangetime = computed<[Date, Date]>({
    get() {
        return [dayjs(ruleForm.starttime).toDate(), dayjs(ruleForm.endtime).toDate()]
    },
    set(e) {
        ruleForm.starttime = e[0]; ruleForm.endtime = e[1]
    }
})
const rule = ref<typeof ElForm>();

const _ruleForm = reactive<Studycodemodel.Iquestion>({})

/**
 * 跳转
 */
async function next(num: 0 | 1 | 2 | 3 | 4) {
    if (num === 0) {
        active.value = String(num)
        successstatus.value = ['finish', 'wait', 'wait', 'wait']
    } else {
        rule.value?.validateField(['name'], (a: boolean, ValidateFieldsError?: string) => {
            if (a) {
                active.value = String(num)
                if (num === 1) {
                    successstatus.value = ['success', 'finish', 'wait', 'wait']
                }
                if (num === 2) {
                    successstatus.value = ['success', 'success', 'finish', 'wait']
                }
                if (num === 3) {
                    successstatus.value = ['success', 'success', 'success', 'finish']
                }
                if (num === 4) {
                    successstatus.value = ['success', 'success', 'success', 'success']
                }
            }
        })

    }
}

async function submit() {
    const n = ruleForm.teamjobrelation?.filter(z => {
        const t = questionid.value.find(n => n.ID === z.questionid)
        const o = users.value.find(([_i, n]) => n === z.userid)
        return t && o
    }) || []
    ruleForm.teamid = p.teamid
    if (!num.value) {
        ruleForm.questionnum = num2.value
    } else {
        if (ruleForm.type === 'question') {
            ruleForm.questionnum = questionid.value.length
        } else if (ruleForm.type === 'video') {
            ruleForm.questionnum = courses.value.length
        } else if (ruleForm.type === 'file') {
            ruleForm.questionnum = teamfile.value.length
        }
    }

    ruleForm.endtime = new Date(dayjs(ruleForm.endtime).unix() * 1000)
    const _user = ruleForm.isall ? p.teamusers.map(e => [0, Number(e.userid)]) : users.value
    for (const [_i, user] of _user) {
        if (ruleForm.type === 'question') {
            forEach(questionid.value, (question, k) => {
                const data: Studycodemodel.Iteamjobrelation = {
                    questionid: question.ID,
                    userid: user,
                    state: false,
                }
                const t = n.find(e => {
                    return e.userid === user && e.questionid === question.ID
                })
                if (!t) {
                    n.push(data)
                }
            })

        } else if (ruleForm.type === 'video') {
            for (const course of courses.value) {
                const data: Studycodemodel.Iteamjobrelation = {
                    courseid: course.ID,
                    userid: user,
                    state: false,
                    catebagid: (course as any).catebagid
                }
                const t = n.find(e => {
                    return e.userid === user && e.courseid === course.ID
                })
                if (!t) {
                    n.push(data)
                }
            }
        } else if (ruleForm.type === 'file') {
            for (const course of teamfile.value) {
                const data: Studycodemodel.Iteamjobrelation = {
                    teamfileid: course.ID,
                    userid: user,
                    state: false,
                }
                const t = n.find(e => {
                    return e.userid === user && e.teamfileid === course.ID
                })
                if (!t) {
                    n.push(data)
                }
            }
        }
    }
    if (!team.value) {
        ElMessage.error('没有此团队')
        return
    }
    if (ruleForm.isall) {
        if (ruleForm.type === 'question') {
            for (const question of questionid.value) {
                const data: Studycodemodel.Iteamjobrelation = {
                    questionid: question.ID,
                    userid: team.value.userid,
                    state: false
                }
                const t = n.find(e => {
                    return e.userid === team.value?.userid && e.questionid === question.ID
                })
                if (!t) {
                    n.push(data)
                }
            }
        } else if (ruleForm.type === 'video') {
            for (const course of courses.value) {
                const data: Studycodemodel.Iteamjobrelation = {
                    courseid: course.ID,
                    userid: team.value.userid,
                    state: false,
                    catebagid: (course as any).catebagid
                }
                const t = n.find(e => {
                    return e.userid === team.value?.userid && e.courseid === course.ID
                })
                if (!t) {
                    n.push(data)
                }
            }
        } else if (ruleForm.type === 'file') {
            for (const course of teamfile.value) {
                const data: Studycodemodel.Iteamjobrelation = {
                    teamfileid: course.ID,
                    userid: team.value.userid,
                    state: false,
                }
                const t = n.find(e => {
                    return e.userid === team.value?.userid && e.teamfileid === course.ID
                })
                if (!t) {
                    n.push(data)
                }
            }
        }
    }
    if (ruleForm.type === 'question') {
        ruleForm.jobquestion = questionid.value.map((e, k) => {
            return {
                questionid: e.ID,
                index: k
            }
        })

    } else if (ruleForm.type === 'video') {
        ruleForm.jobquestion = courses.value.map((e, k) => {
            return {
                catebagid: (e as any).catebagid,
                index: k,
                courseid: e.ID,
            }
        })
    } else if (ruleForm.type === 'file') {
        ruleForm.jobquestion = teamfile.value.map((e, k) => {
            return {
                index: k,
                teamfileid: e.ID,

            }
        })
    }
    ruleForm.teamjobrelation = n
    asyncteamcreatedorupdatedteamjob(ruleForm).then(e => {
        router.push(p.roure)
    }).catch(e => {
        ElMessage.error(e)
    })
}

function removeclick(index: number) {
    questionid.value.splice(index, 1)
}

function removeclickcourse(index: number) {
    courses.value.splice(index, 1)
}

function removeclickteamfile(index: number) {
    teamfile.value.splice(index, 1)
}

function addclick(v: Studycodemodel.Iquestion) {
    const n = questionid.value.find(t => t.ID === v.ID)
    if (!n) {
        questionid.value.push(v)
    }
}

function addclickcourse(v: Alymodel.IMcourse) {
    const n = courses.value.find(t => t.ID === v.ID)
    if (!n) {
        courses.value.push(v)
    }
}

function addclickteamfile(v: Studycodemodel.Iteamfile) {
    const n = teamfile.value.find(t => t.ID === v.ID)
    if (!n) {
        teamfile.value.push(v)
    }
}


onMounted(() => {
    start()
})




async function start() {
    if (p.data) {
        Object.assign(ruleForm, p.data)
        users.value = uniq(p.data.teamjobrelation?.map(e => e.userid).map(e => [0, Number(e)]) || [])
        const ID = Object.keys(groupBy(p.data.teamjobrelation || [], e => Number(e.questionid)))
        questionid.value = p.question.filter(e => ID.find(v => Number(v) === e.ID)).sort((a, b) => {
            const a_index = ruleForm?.jobquestion?.find(c => c.questionid === a.ID)?.index || 0
            const b_index = ruleForm?.jobquestion?.find(c => c.questionid === b.ID)?.index || 0
            return a_index - b_index
        })
        if (ruleForm.type === 'question') {
            num.value = ruleForm.questionnum == questionid.value.length
            num2.value = Number(ruleForm.questionnum)
        } else if (ruleForm.type === 'video') {
            const courseid = p.data.teamjobrelation?.map(e => e.courseid)
            if (courseid?.length) {
                asyncselectcourse({ teamid: p.teamid, ID: courseid }).then(e => {
                    courses.value = e.rows.sort((a, b) => {
                        const a_index = ruleForm?.jobquestion?.find(c => c.courseid === a.ID)?.index || 0
                        const b_index = ruleForm?.jobquestion?.find(c => c.courseid === b.ID)?.index || 0
                        return a_index - b_index
                    }).map(c => {
                        const catebagid = p.data?.teamjobrelation?.find(e => e.courseid === c.ID)
                        return {
                            ...c,
                            catebagid: catebagid?.catebagid
                        }
                    })
                    num.value = ruleForm.questionnum == courses.value.length
                    num2.value = Number(ruleForm.questionnum)
                })
            }
        } else if (ruleForm.type === 'file') {
            const teamfileid = p.data.teamjobrelation?.map(e => e.teamfileid)
            if (teamfileid?.length) {
                asyncgetteamfile({ teamid: p.teamid, ID: teamfileid }).then(e => {
                    teamfile.value = e.rows.sort((a, b) => {
                        const a_index = ruleForm?.jobquestion?.find(c => c.teamfileid === a.ID)?.index || 0
                        const b_index = ruleForm?.jobquestion?.find(c => c.teamfileid === b.ID)?.index || 0
                        return a_index - b_index
                    })
                    num.value = ruleForm.questionnum == teamfile.value.length
                    num2.value = Number(ruleForm.questionnum)
                })
            }

        }


    }
}

watch(() => p.data, e => {
    start()
})



// 修改题目列表
function changequestionid(v: Studycodemodel.Iquestion[]) {
    questionid.value = v
}

function chagecourse(v: Alymodel.IMcourse[]) {
    courses.value = v
}


function chageteamfile(v: Studycodemodel.Iteamfile[]) {
    teamfile.value = v
}

</script>

<style scoped>
.demo-ruleForm {
    margin-top: 24px;
}

.el-upload-list__item-thumbnail {
    background-repeat: no-repeat;
    background-size: 100% 100%;
    text-align: center;
    line-height: 180px;
    color: rgba(0, 0, 0, 0);
}

.el-upload-list__item-thumbnail:hover div {
    color: #fff;
    background-color: rgba(31, 31, 31, 0.8);
}
</style>
